package com.water.app.Config;

import com.water.app.Exceptions.BalanceException;
import com.water.app.Exceptions.DeleteException;
import com.water.app.Exceptions.StockException;
import com.water.app.Exceptions.isPassException;
import com.water.app.Result;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class CatchException {

    @ExceptionHandler(Exception.class)
    public Result HandleException(Exception e){
        return Result.error(e.getMessage());
    }

    // 专门捕获 DuplicateKeyException 异常
    @ExceptionHandler(DuplicateKeyException.class)
    public Result handleDuplicateKeyException(DuplicateKeyException e) {
        // 提取异常信息，判断是否为商品名称重复
        String message = e.getMessage();
        if (message.contains("Duplicate entry") && message.contains("goods.name")) {
            // 返回友好提示：商品名称已存在
            return Result.error("商品名称已存在，请更换名称后重试");
        }
        // 其他唯一键冲突（如用户名重复），返回通用提示
        return Result.error("数据已存在，操作失败");
    }
    @ExceptionHandler(BalanceException.class)
    public Result HandleBalanceException(BalanceException e){
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(StockException.class)
    public Result HandleStockException(StockException e){return Result.error(e.getMessage());}

    @ExceptionHandler(DeleteException.class)
    public Result HandleDeleteException(DeleteException e){
        return Result.error(e.getMessage());
    }

    @ExceptionHandler(isPassException.class)
    public Result HandleIsPassException(isPassException e){
        return Result.error(e.getMessage());
    }
}
